package com.hzit.loan.task.job;

import com.hzit.loan.pay.commonApi.enums.PayChannelEnum;
import com.hzit.loan.pay.commonApi.resp.PayNotifyData;
import com.hzit.loan.pay.commonApi.resp.RespVo;
import com.hzit.loan.pay.commonApi.resp.TaskTradeQueryRespData;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 支付宝交易查询定时任务
 * 每隔5分钟执行一次
 *
 */
@Component
public class AlipayTradeQueryJob {


    @Autowired
    private RestTemplate restTemplate;

    private Logger logger = LoggerFactory.getLogger(AlipayTradeQueryJob.class);


    @XxlJob("alipayTradeQuery")
    public ReturnT<String> execute(String param){


        //1.获取支付流水表中的，未支付，和支付中的数据，：hzit-loan-pay： queyTrading

        String url = "http://HZIT-LOAN-PAY/task/queyTrading?payChannel="+ PayChannelEnum.ALIPAY.getCode();

        RespVo<List<TaskTradeQueryRespData>> respVo = restTemplate.getForObject(url, RespVo.class);

        if (0 !=respVo.getCode()){
            logger.info("调用HZIT-LOAN-PAY服务失败：{}",respVo.getMsg());
            return ReturnT.FAIL;
        }

        List<TaskTradeQueryRespData> dataList = respVo.getData();

        if (CollectionUtils.isEmpty(dataList)){
            logger.info("########dataList为空#########");
            return ReturnT.SUCCESS;
        }


        for (TaskTradeQueryRespData queryRespData :dataList){

            String paySerialNo = queryRespData.getPaySerialNo();
            String forntUrl = "http://ALIPAY-FRONT/alipayFront/query?paySeiralNo="+ paySerialNo;


            //2.调用支付宝查询接口 ： ALIPAY-FRONT
            RespVo<PayNotifyData> respVo1 = restTemplate.getForObject(forntUrl,RespVo.class);

            //3.解析支付宝回来的结果 ：
            if (0 != respVo1.getCode()){
                logger.info("调用前置服务异常：{}",respVo1.getMsg());
                continue;
            }

            PayNotifyData payNotifyData = respVo1.getData();

            String updateUrl = "http://HZIT-LOAN-PAY/task/updateTrading";

            //4.更新支付流水表中的状态  hzit-loan-pay, UPDATE
            String rlt = restTemplate.postForObject(updateUrl,payNotifyData,String.class);
            logger.info("调用支付服务更新流水：{}，结果：{}",payNotifyData.getPaySerialNo(),rlt);

        }

        return ReturnT.SUCCESS;
    }
}
